package com.yiboshi.rehrs.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class SHA256Util {

    private static final Logger logger = LoggerFactory.getLogger(SHA256Util.class);

    static String sign = "DE6xZ>AjA%EJv2hJ=*2kfP@4wYr%A#A9";
    public static String Jdpt_sign(String currentTimeMillis, String pda_user_token, String person_no) {
        return getSHA256("jdpt_req_time=" + currentTimeMillis + "&pda_user_token=" + pda_user_token + "&person_no=" + person_no + "&thirdKey=DE6xZ>AjA%EJv2hJ=*2kfP@4wYr%A#A9"
             ,sign   );
    }

    //默认
   static SecretKeySpec secretKeySpec = new SecretKeySpec(sign.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
    public static String getSHA256(String str,String sign) {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(secretKeySpec);
            byte[] doFinal = mac.doFinal(str.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder(64);
            for (byte b : doFinal) {
                String hexString = Integer.toHexString(b & 0xFF);
                if (hexString.length() == 1) {
                    sb.append('0');
                }
                sb.append(hexString);
            }
            return sb.toString();
        } catch (InvalidKeyException | NoSuchAlgorithmException e) {
            logger.error("Error in getSHA256 method", e);
            return "";
        }
    }

    public static void main(String[] args) {
        // 测试代码
        String input = "Hello, World!";
        String key = "secretkey";
        String result = getSHA256(input, key);
        System.out.println("HMAC-SHA256: " + result);
    }
}
